package com.egao.platform.system.controller;

import cn.hutool.core.util.StrUtil;
import com.egao.platform.common.annotation.ApiPageParam;
import com.egao.platform.common.core.*;
import com.egao.platform.system.entity.User;
import com.egao.platform.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by wangfan on 2018-12-24 16:10
 */
@Api(tags = "用户管理")
@RestController
@RequestMapping("/api/sys/user")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;

    @ApiOperation("分页查询用户")
    @ApiPageParam
    @GetMapping("/page")
    public PageResult<User> page(HttpServletRequest request) {
        PageParam<User> pageParam = new PageParam<>(request);
        pageParam.setDefaultOrder(null, new String[]{"create_time"});
        return userService.listPage(pageParam);
    }

    @ApiOperation("根据id查询用户")
    @GetMapping("/{id}")
    public JsonResult get(@PathVariable("id") Integer id) {
        PageParam<User> pageParam = new PageParam<>();
        pageParam.put("userId", id);
        List<User> records = userService.listAll(pageParam.getNoPageParam());
        return JsonResult.ok().setData(pageParam.getOne(records));
    }

    @ApiOperation("查询全部用户")
    @GetMapping()
    public JsonResult list(HttpServletRequest request) {
        PageParam<User> pageParam = new PageParam<>(request);
        List<User> records = userService.listAll(pageParam.getNoPageParam());
        return JsonResult.ok().setData(pageParam.sortRecords(records));
    }

    @ApiOperation("添加用户")
    @PostMapping()
    public JsonResult add(@RequestBody User user) {
        user.setState(0);
        user.setPassword(userService.md5Psw(user.getPassword()));
        if (userService.addUser(user)) {
            return JsonResult.ok("添加成功");
        }
        return JsonResult.error("添加失败");
    }

    @ApiOperation("修改用户")
    @PutMapping()
    public JsonResult update(@RequestBody User user) {
        user.setState(null);
        user.setPassword(userService.md5Psw(user.getPassword()));
        if (userService.updateUser(user)) {
            return JsonResult.ok("修改成功");
        }
        return JsonResult.error("修改失败");
    }

    @ApiOperation("删除用户")
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Integer id) {
        if (userService.removeById(id)) {
            return JsonResult.ok("删除成功");
        }
        return JsonResult.error("删除失败");
    }

    @ApiOperation("批量添加用户")
    @PostMapping("/batch")
    public JsonResult saveBatch(@RequestBody List<User> userList) {
        if (userService.saveBatch(userList)) {
            return JsonResult.ok("添加成功");
        }
        return JsonResult.error("添加失败");
    }

    @ApiOperation("批量修改用户")
    @PutMapping("/batch")
    public JsonResult updateBatch(@RequestBody BatchParam batchParam) {
        if (batchParam.update(userService, "user_id", User.class)) {
            return JsonResult.ok("修改成功");
        }
        return JsonResult.error("修改失败");
    }

    @ApiOperation("批量删除用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "id数组", required = true, dataType = "string")
    })
    @DeleteMapping("/batch")
    public JsonResult deleteBatch(@RequestBody List<Integer> ids) {
        if (userService.removeByIds(ids)) {
            return JsonResult.ok("删除成功");
        }
        return JsonResult.error("删除失败");
    }

    @ApiOperation("修改用户状态")
    @PutMapping("/state/{id}")
    public JsonResult updateState(@PathVariable("id") Integer id, Integer state) {
        if (state == null || (state != 0 && state != 1)) {
            return JsonResult.error("状态值不正确");
        }
        User user = new User();
        user.setUserId(id);
        user.setState(state);
        if (userService.updateById(user)) {
            return JsonResult.ok("修改成功");
        }
        return JsonResult.error("修改失败");
    }

    @ApiOperation("批量修改用户状态")
    @PutMapping("/state/batch")
    public JsonResult updateStateBatch(BatchParam batchParam) {
        batchParam.setField("state");
        Integer state = batchParam.getInteger();
        if (state == null || (state != 0 && state != 1)) {
            return JsonResult.error("状态值不正确");
        }
        if (batchParam.update(userService, "user_id", User.class)) {
            return JsonResult.ok("修改成功");
        }
        return JsonResult.error("修改失败");
    }

    @ApiOperation("重置密码")
    @PutMapping("/psw/{id}")
    public JsonResult resetPsw(@PathVariable("id") Integer id, String password) {
        User user = new User();
        user.setUserId(id);
        user.setPassword(userService.md5Psw(password));
        if (userService.updateById(user)) {
            return JsonResult.ok("重置成功");
        } else {
            return JsonResult.error("重置失败");
        }
    }

    @ApiOperation("批量重置密码")
    @PutMapping("/psw/batch")
    public JsonResult resetPswBatch(BatchParam batchParam) {
        batchParam.setField("password");
        batchParam.setValue(userService.md5Psw(batchParam.getString()));
        if (batchParam.update(userService, "user_id", User.class)) {
            return JsonResult.ok("重置成功");
        } else {
            return JsonResult.error("重置失败");
        }
    }

    @ApiOperation("修改自己密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "oldPsw", value = "旧密码", required = true, dataType = "string"),
            @ApiImplicitParam(name = "newPsw", value = "新密码", required = true, dataType = "string")
    })
    @PutMapping("/psw")
    public JsonResult updatePsw(String oldPsw, String newPsw, HttpServletRequest request) {
        if (StrUtil.hasBlank(oldPsw, newPsw)) {
            return JsonResult.error("参数不能为空");
        }
        if (getLoginUserId(request) == null) {
            return JsonResult.error("未登录");
        }
        if (!userService.comparePsw(oldPsw, userService.getById(getLoginUserId(request)).getPassword())) {
            return JsonResult.error("原密码输入不正确");
        }
        User user = new User();
        user.setUserId(getLoginUserId(request));
        user.setPassword(userService.md5Psw(newPsw));
        if (userService.updateById(user)) {
            return JsonResult.ok("修改成功");
        }
        return JsonResult.error("修改失败");
    }

}
